package com.ruoyix.weblog.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyix.weblog.domain.UploadPO;
import com.ruoyix.weblog.domain.bo.BlogVideosBo;
import com.ruoyix.weblog.domain.vo.BlogVideosVo;
import com.ruoyix.weblog.service.IBlogVideosService;
import com.ruoyix.weblog.service.impl.BlogVideosServiceImpl;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyix.common.annotation.RepeatSubmit;
import com.ruoyix.common.annotation.Log;
import com.ruoyix.common.core.controller.BaseController;
import com.ruoyix.common.core.domain.PageQuery;
import com.ruoyix.common.core.domain.R;
import com.ruoyix.common.core.validate.AddGroup;
import com.ruoyix.common.core.validate.EditGroup;
import com.ruoyix.common.core.validate.QueryGroup;
import org.springframework.core.io.Resource;
import com.ruoyix.common.enums.BusinessType;
import com.ruoyix.common.utils.poi.ExcelUtil;

import com.ruoyix.common.core.page.TableDataInfo;

/**
 * 视频管理
 *
 * @author ruoyi
 * @date 2024-09-06
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/weblog/blogVideos")
public class BlogVideosController extends BaseController {

    private final IBlogVideosService iBlogVideosService;

    private final ResourceLoader resourceLoader;

    /**
     * 查询视频管理列表
     */
    @SaCheckPermission("weblog:blogVideos:list")
    @GetMapping("/list")
    public TableDataInfo<BlogVideosVo> list(BlogVideosBo bo, PageQuery pageQuery) {
        return iBlogVideosService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出视频管理列表
     */
    @SaCheckPermission("weblog:blogVideos:export")
    @Log(title = "视频管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BlogVideosBo bo, HttpServletResponse response) {
        List<BlogVideosVo> list = iBlogVideosService.queryList(bo);
        ExcelUtil.exportExcel(list, "视频管理", BlogVideosVo.class, response);
    }

    /**
     * 获取视频管理详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("weblog:blogVideos:query")
    @GetMapping("/{id}")
    public R<BlogVideosVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iBlogVideosService.queryById(id));
    }

    /**
     * 新增视频管理
     */
    @SaCheckPermission("weblog:blogVideos:add")
    @Log(title = "视频管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BlogVideosBo bo) {
        return toAjax(iBlogVideosService.insertByBo(bo));
    }

    /**
     * 修改视频管理
     */
    @SaCheckPermission("weblog:blogVideos:edit")
    @Log(title = "视频管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BlogVideosBo bo) {
        return toAjax(iBlogVideosService.updateByBo(bo));
    }

    /**
     * 删除视频管理
     *
     * @param ids 主键串
     */
    @SaCheckPermission("weblog:blogVideos:remove")
    @Log(title = "视频管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iBlogVideosService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    /**
     * 上传分片前校验文件是否存在
     *
     * @return
     */
    @GetMapping("/preUpload")
    public R<String> preUpload(@RequestParam("fileMd5") String fileMd5) {
        return iBlogVideosService.checkExists(fileMd5);
    }

    /**
     * 上传分片
     *
     * @return
     */
    @PostMapping("/upload")
    public R<String> fragmentation(@ModelAttribute UploadPO uploadPO) {
        return iBlogVideosService.uploadChunk(uploadPO);
    }

    @SaIgnore
    @GetMapping("/show/{md5}/{m3u8}")
    public ResponseEntity<Resource> getM3u8Stream(@PathVariable String md5,@PathVariable String m3u8) throws IOException {
        // 这里假设m3u8文件在项目的resources目录下

        InputStream inputStream = Files.newInputStream(Paths.get(BlogVideosServiceImpl.getFilePath() + File.separator + "video" + File.separator + "m3u8Dir" + File.separator + md5 + File.separator + m3u8));
        Resource resource = new InputStreamResource(inputStream);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"));
        headers.setContentDispositionFormData("attachment", "m3u8file.m3u8");

        return ResponseEntity.ok()
            .headers(headers)
            .body(resource);
    }

    @GetMapping("/getKey")
    public ResponseEntity<byte[]> getKey() {
        try {
            // 使用 ClassPathResource 读取 resources 目录下的 enc.key 文件
            ClassPathResource resource = new ClassPathResource("enc.key");
            Path path = Paths.get(resource.getURI());

            // 将文件内容读取为字节数组
            byte[] keyBytes = Files.readAllBytes(path);

            // 设置响应头，返回文件内容
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=enc.key");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");

            return new ResponseEntity<>(keyBytes, headers, HttpStatus.OK);

        } catch (IOException e) {
            // 处理异常情况
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
